<template>
  <div>
    <label for="fileInput">
      <div class="img">
        <div id="Box">
          <img :src="ImgSrc" alt="头像上传" />
        </div>
        <button @click="uploadAvatar">上传</button>
      </div>
    </label>
    <div class="username">
      <input type="file" @change="showPicture()" id="fileInput" />
    </div>
  </div>
</template>

<script>
import Bus from '../bus'
export default {
  data() {
    return {
      ImgSrc: ''
    }
  },
  computed: {
    input() {
      return document.querySelector('#fileInput')
    }
  },
  methods: {
    uploadAvatar() {
      console.log(this.input.files[0])
      if (this.input.files[0]) {
        if (this.input.files[0].size / 1024 > 2000) {
          alert('文件大小不能超过2m')
          Bus.$emit('finishChange', 'error')
          return false
        }
        let aa = this.input.files[0].name.split('.')
        if (aa[aa.length - 1] == 'jpg' || aa[aa.length - 1] == 'webp' || aa[aa.length - 1] == 'png' || aa[aa.length - 1] == 'jpeg') {
          const data = new FormData()
          data.append('imgfile', this.input.files[0])
          data.append('username', this.$store.getters.user.username)
          this.$axios
            .post('/upload/up', data, {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            })
            .then(res => {
              console.log(res)
              this.$store.dispatch('setUserAvatar', res.data.message)
              Bus.$emit('finishChange', 'success')
            })
        } else {
          alert('只允许jpg,jepg,png,bmp格式的图片')
          Bus.$emit('finishChange', 'error')
        }
      }
    },

    showPicture() {
      console.log(this.input.files)
      let url = window.webkitURL || window.URL
      let imgfileurl = url.createObjectURL(this.input.files[0])
      this.ImgSrc = imgfileurl
    }
  }
}
</script>

<style lang="less" scoped>
.img {
  display: flex;
  justify-content: space-between;
  align-items: center;
  button {
    border: 2px solid black;
    width: 50px;
    height: 30px;
    outline: none;
    border-radius: 30px;
    transition: all 0.4s;
    &:hover {
      background-color: black;
      color: #fff;
    }
  }
}
#Box {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  background-color: #fff;
  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
}
input {
  display: none;
}
</style>